/*
 * Copyright 2012 Faculty of Informatics - Masaryk University.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.pa165.creatures.rest.client.services.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;

/**
 * Sends an HTTP method and operates upon a result accordingly.
 *
 * If a result code is 200, it prints what it got, otherwise error code
 * is written out which can be accompanied with brief informational message
 * what has happened.
 *
 * @author smikloso
 */
public class CRUDServiceHelper {

    private static final Logger logger =
            Logger.getLogger(CRUDServiceHelper.class.getName());

    private static final String CONNECTION_EXCEPTION_MSG =
            "Unsuccessful in contacting the server. It may be offline.";

    private static final String RESPONSE_STATUS_CODE = "Response status code: ";

    private static final String RESPONSE_HEADER = "Response headers: ";

    /**
     * Helper methods which executes an HTTP {@code method} and writes the
     * output to the standard output (e.g. console). Return codes of the HTTP
     * responses are present so we can verify what happened at the server side.
     *
     * @param method method to send to the server side
     */
    public static void send(HttpMethodBase method) {
        HttpClient httpClient = new HttpClient();
        try {

            int result = httpClient.executeMethod(method);
            System.out.println(RESPONSE_STATUS_CODE + result);
            ResponseCode response = ResponseCode.fromInt(result);
            if (response != ResponseCode.NOT_FOUND
                    && response != ResponseCode.SERVER_ERROR
                    && response != ResponseCode.FORBIDDEN) {
                System.out.println(RESPONSE_HEADER);

                Header[] headers = method.getResponseHeaders();
                for (Header h : headers) {
                    System.out.println(h.toString());
                }

                InputStreamReader isr =
                        new InputStreamReader(method.getResponseBodyAsStream());
                BufferedReader br = new BufferedReader(isr);

                String line;

                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }
        } catch (ConnectException ex) {
            logger.log(Level.WARNING, CONNECTION_EXCEPTION_MSG);
        } catch (IOException ex) {
            logger.log(Level.INFO, ex.getMessage());
        } finally {
            method.releaseConnection();
        }
    }
}
